<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { toNumber } from 'lodash-es'
import { GetConfigurationList, GetData, PatchModifyType } from '@/api/modules/messageGroup'

// const imgDomain = 'https://img1.eprhan.cc'
const router = useRouter()

const findFrom = ref({
  GroupName: '',
  Type: '',
  Enable: '',
})
const dataList: any = ref([])
const loading = ref(true)
const total = ref(0)
let PageSize = 20
let PageNum = toNumber(localStorage.getItem('currentPage')) || 1

async function GetDataList(PageIndex: number = 1, PageSize: number = 20) {
  const params = {
    PageIndex,
    PageSize,
    ...(findFrom.value.GroupName && ({ GroupName: findFrom.value.GroupName })),
    ...(findFrom.value.Type && ({ Type: findFrom.value.Type })),
    ...(findFrom.value.Enable && ({ Enable: findFrom.value.Enable })),
  }
  await GetData(params).then(async (dataRes: any) => {
    if (dataRes.succeeded) {
      await GetConfigurationList().then((res: any) => {
        if (res.succeeded) {
          dataList.value = dataRes.data.items

          dataList.value.forEach((item: any) => {
            const configMap = new Map(res.data.map((item: any) => [item.id, item]))
            item.relateConfigArray = item.relateConfigArray.map((id: number) => {
              return configMap.get(toNumber(id))
            }).filter((obj: any) => obj !== undefined)
          })
          total.value = dataRes.data.total
          loading.value = false
        }
      })
    }
  })
  loading.value = false
}
// 查询
function Inquire() {
  GetDataList(1, PageSize)
}

// 修改状态
async function ModifyType(params: any) {
  await PatchModifyType(params).then((res: any) => {
    if (res.statusCode === 200) {
      ElMessage.success('修改成功')
      GetDataList(PageNum, PageSize)
    }
    else {
      ElMessage.error('修改失败', res.errors)
    }
  })
}
// 添加
function AddData() {
  router.push({
    name: 'messageGroupDetail',
  })
}
// 编辑
function EditData(id: number) {
  localStorage.setItem('currentPage', `${PageNum}`)
  router.push({
    name: 'messageGroupDetail',
    query: {
      id,
    },
  })
}

// 翻页
function handleSizeChange(val: number) {
  GetDataList(1, val)
  PageSize = val
}
function handleCurrentChange(val: number) {
  GetDataList(val, PageSize)
  PageNum = val
}

const nowPageNum = computed(() => {
  return toNumber(localStorage.getItem('currentPage')) || 1
})

onMounted(() => {
  if (localStorage.getItem('currentPage') !== null) {
    GetDataList(toNumber(localStorage.getItem('currentPage')), 20)
    localStorage.removeItem('currentPage')
  }
  else {
    GetDataList()
  }
})
</script>

<template>
  <div>
    <PageMain>
      <SearchBar :show-toggle="false">
        <div class="header">
          <el-form label-positio="right" label-width="auto">
            <div class="from">
              <el-form-item label="组名">
                <el-input v-model="findFrom.GroupName" placeholder="请输入组名" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="类型">
                <el-select v-model="findFrom.Type" placeholder="请选择" clearable>
                  <el-option label="企微欢迎语" :value="1" />
                  <el-option label="快捷消息" :value="2" />
                  <el-option label="灵活欢迎语" :value="3" />
                </el-select>
              </el-form-item>
              <el-form-item label="是否启用">
                <el-select v-model="findFrom.Enable" placeholder="请选择" clearable>
                  <el-option label="是" :value="1" />
                  <el-option label="否" :value="0" />
                </el-select>
              </el-form-item>
            </div>
          </el-form>
          <div class="text-right">
            <el-button @click="Inquire">
              查询
            </el-button>
          </div>
        </div>
      </SearchBar>
      <ElDivider border-style="dashed" />
      <div class="mb-5 text-right">
        <el-button type="success" @click="AddData">
          添加
        </el-button>
      </div>
      <el-table v-loading="loading" :data="dataList" stripe style="width: 100%;" border>
        <el-table-column header-align="center" prop="groupName" label="组名" width="240" />
        <el-table-column align="center" prop="avatar" label="类别" width="160">
          <template #default="scope">
            <el-tag>
              {{ scope.row.type === 1 ? '企微欢迎语'
                : scope.row.type === 2 ? '快捷消息'
                  : scope.row.type === 3 ? '灵活欢迎语' : '未知' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column header-align="center" prop="relateConfigArray" label="关联配置">
          <template #default="scope">
            <span v-for="(item, index) in scope.row.relateConfigArray" :key="item.id">
              {{ item.title }}
              <span v-if="index !== scope.row.relateConfigArray.length - 1">，</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" width="200" prop="enable" label="是否启用">
          <template #default="scope">
            <el-switch
              v-model="scope.row.enable"
              :active-value="true"
              :inactive-value="false"
              @click="ModifyType({ id: scope.row.id, enable: scope.row.enable })"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" fixed="right" width="260">
          <template #default="scope">
            <el-button type="primary" @click="EditData(scope.row.id)">
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="height: 10px;" />
      <el-pagination
        :default-page-size="20"
        :page-sizes="[5, 10, 20, 50, 100]"
        layout="total, sizes, ->, prev, pager, next, jumper"
        :total="total"
        :default-current-page="nowPageNum"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </PageMain>
  </div>
</template>

<style scoped>
.header {
  display: grid;
  grid-template-columns: 6fr 1fr;

  .from {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    grid-gap: 20px;

    .el-form-item {
      margin-bottom: 0;
    }
  }
}
</style>
